package com.qianniu.napi.admin.web;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.entity.penum.Gstatus;
import com.qianniu.napi.admin.entity.penum.PTstatus;
import com.qianniu.napi.admin.entity.penum.StatusEnum;
import com.qianniu.napi.admin.entity.penum.YXType;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.common.util.DateUtil;
import com.qianniu.napi.common.util.ObjectUtil;
import com.qianniu.napi.common.util.RandSplitNumUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static java.math.BigDecimal.ROUND_HALF_DOWN;

/**
 * <p>
 * 发起砍价活动
 * </p>
 *
 * @author chenxuebin
 * @since 2018-07-14
 */
@RestController
public class CutpriceOpenController {

    private static final Logger logger = LoggerFactory.getLogger(CutpriceOpenController.class);

    @Autowired
    private IOrderService orderService;
    @Autowired
    private ICutpriceService cutpriceService;
    @Autowired
    private ICutpriceOpenService cutpriceOpenService;
    @Autowired
    private ICutpriceHelpService cutpriceHelpService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IOrderGoodsService orderGoodsService;

    @RequestMapping("/api/cutprice/my/list")
    @ResponseBody
    public Jinfo myCutpriceList(@RequestParam(value = "suid", required = false) Long suid,
                                @RequestParam(value = "participantId", required = false) Long participantId,
                                @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                                @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                HttpServletRequest req) {
        Jinfo info = new Jinfo();
        if (pageSize == null) pageSize = 10;

        Page page = new Page(pageIndex, pageSize);
        if (suid != null && suid != 0) {
            page = cutpriceOpenService.selectPage(page, new EntityWrapper<CutpriceOpen>()
                    .eq("uid", suid));
            info.setInfo(page.getRecords());
        } else if (participantId != null && participantId != 0) {
            logger.debug(">>>participantId=" + participantId);
            logger.debug(">>>pageSize=" + pageSize);
            logger.debug(">>>pageIndex=" + pageIndex);
            logger.debug(">>>ObjectUtil.getUid()=" + ObjectUtil.getUid());

            info.setInfo(cutpriceOpenService.getMyCutpriceOpen(page, ObjectUtil.getUid()));
        }

        return info;
    }

    @RequestMapping("/api/cutpriceopen/list")
    @ResponseBody
    public Jinfo list(@RequestParam(value = "status", required = false) String status,
                      @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                      @RequestParam(value = "pageSize", required = false) Integer pageSize,
                      HttpServletRequest req) {
        Jinfo info = new Jinfo();
        if (pageSize == null) pageSize = 10;
        Page page = new Page(pageIndex, pageSize);
        page = cutpriceOpenService.selectPage(page, new EntityWrapper<CutpriceOpen>()
                .eq("uid", ObjectUtil.getUid())
                .eq("state", 1));
        info.setInfo(page.getRecords());
        return info;
    }

    @RequestMapping("/api/cutprice/event/list")
    @ResponseBody
    public Jinfo cutpriceEventList(@RequestParam(value = "isnew", required = false) int isnew,
                                   @RequestParam(value = "status", required = false) String status,
                                   @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                                   @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                   HttpServletRequest req) {

        Jinfo info = new Jinfo();
        if (pageSize == null) pageSize = 10;
        Page page = new Page(pageIndex, pageSize);
        if (isnew == 1) {
//            page = cutpriceService.selectPage(page, new EntityWrapper<Cutprice>()
            // 凡是 status==1 的砍价视为商户刚刚发布的砍价活动，暂无
            // 别人发起的砍价活动
            page = cutpriceOpenService.selectPage(page, new EntityWrapper<CutpriceOpen>()
                    .eq("status", 2)
                    .eq("mid", ObjectUtil.getMid())
                    .eq("state", 1)
                    .orderBy("id"));
        } else {
            // 自己发起的砍价活动
            page = cutpriceOpenService.selectPage(page, new EntityWrapper<CutpriceOpen>()
                    .eq("status", 2)
                    .ne("uid", ObjectUtil.getUid())
                    .eq("state", 1)
                    .orderBy("id"));
        }

        info.setInfo(page.getRecords());
        return info;
    }

    @RequestMapping("/api/cutprice/for/help")
    @ResponseBody
    public Jinfo cutpriceHelp(@RequestParam("coid") Long coid,
                              @RequestParam("isnew") int isnew,
                              @RequestParam(value = "remark", required = false) String remark,
                              HttpServletRequest req
    ) {
        Jinfo info = new Jinfo();
//        List<CutpriceHelp> list = cutpriceHelpService.selectList();
        CutpriceOpen cutpriceopen = cutpriceOpenService.selectById(coid);
        int number = cutpriceopen.getNumber();
        double leftprice = cutpriceopen.getCurprice().subtract(cutpriceopen.getMinprice()).doubleValue();
        BigDecimal cut = null;
        if (number >= 10) {
            cut = new BigDecimal(leftprice);
        } else {
            // 系统默认10次砍价完成
            Random ran = new Random();
            cut = new BigDecimal(leftprice).divide(new BigDecimal(ran.nextInt(11 - number) + 1), 2, ROUND_HALF_DOWN);
        }
        // 更新当前砍价活动实例t_cutprice_open
        cutpriceopen.setNumber(number + 1);
        cutpriceopen.setTotalcutPrice(cutpriceopen.getTotalcutPrice().add(cut));
        cutpriceopen.setCurprice(cutpriceopen.getCurprice().subtract(cut));
        cutpriceopen.setModifytime(new Date());
        if (isnew == 1) {
            cutpriceopen.setUid(ObjectUtil.getUid());
            cutpriceopen.setStatus(2);
        }

        cutpriceopen.updateById();


        // 插入一次砍价实例t_cutprice_help
        CutpriceHelp help = new CutpriceHelp();
        help.setCoid(coid);
        help.setUid(ObjectUtil.getUid());
        help.setMpid(ObjectUtil.getMpid());
        help.setSid(ObjectUtil.getSid());
        help.setCutprice(cut);

        User userInfo = userService.selectById(help.getUid());

        help.setAvatarpic(userInfo.getAvatarPic());
        help.setNickname(userInfo.getNickName());
        help.setGid(cutpriceopen.getGid());
        help.setRemark(remark);
        help.setCreatetime(new Date());
        help.insert();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("money", cut);
        map.put("cid", cutpriceopen.getCid());
        info.setInfo(map);
        return info;
    }

    @RequestMapping("/api/cutprice/forcut")
    @ResponseBody
    public Jinfo forcut(@RequestParam("ptoid") Long ptoid,
                        @RequestParam(value = "oid", required = false) Long oid,
                        @RequestParam(value = "remark", required = false) String remark
    ) {
        Jinfo info = new Jinfo();
        logger.debug("----------------------ptoid=" + ptoid);
        logger.debug("----------------------oid=" + oid);

        CutpriceOpen cutpriceopen = cutpriceOpenService.selectById(ptoid);
        int cot = cutpriceOpenService.selectCount(new EntityWrapper<CutpriceOpen>().eq("id", ptoid));

        logger.debug("----------------------cutpriceopen=" + JSON.toJSONString(cutpriceopen));

        if (cot == 0 && oid != null) {
            logger.debug("----------------------cutprice/forcut 00000000aaaaaa");
            cutpriceopen = cutpriceOpenService
                    .selectOne(new EntityWrapper<CutpriceOpen>().eq("oid", oid));
            ptoid = cutpriceopen != null ? cutpriceopen.getId() : null;
        }

        if (cutpriceopen == null) {
            logger.debug("----------------------cutprice/forcut 00000000bbbbbbb");
            info.setCode(1);
            info.setMsg("参数有误");
            return info;
        }

        logger.debug("----------------------cutprice/forcut 111111");
        if (cutpriceopen.getStatus().intValue() == PTstatus.ok.getVal()) {
            info.setCode(1);
            info.setMsg("已砍价成功");
            return info;
        }
        Goods goods = goodsService.selectById(cutpriceopen.getGid());
        if (goods == null) {
            info.setCode(4);
            return info;
        }
        Long uid = ObjectUtil.getUid();
        if (uid == null) {
            info.setCode(1);
            info.setMsg("请登录之后再操作");
            return info;
        }
        logger.debug("----------------------cutprice/forcut 2222222 uid="+uid);

        if (cutpriceopen == null) {
            info.setCode(1);
            info.setMsg("参数有误");
            return info;
        }
        int cutcount = cutpriceHelpService.selectCount(new EntityWrapper<CutpriceHelp>()
                .eq("coid", ptoid).eq("uid", uid));
        if (cutcount > 0) {
            info.setCode(1);
            info.setMsg("已帮砍，无法重复砍价");
            return info;
        }
        String cjkey = oid + "_" + goods.getId() + "_" + uid;
        Integer cjval = redisService.get(cjkey);
        if (cjval == null) {
            redisService.set(cjkey, 1, 10, TimeUnit.MINUTES);
        } else {
            info.setCode(1);
            info.setMsg("已帮砍，无法重复砍价");
            return info;
        }

        logger.debug("----------------------cutprice/forcut 333333");

        int number = cutpriceopen.getNumber();
        BigDecimal price = cutpriceopen.getPrice();
        int ptotal = goods.getPtotal();
        boolean kover = false;

        BigDecimal leftprice = cutpriceopen.getCurprice().subtract(cutpriceopen.getMinprice());
        BigDecimal leftprice100 = leftprice.multiply(new BigDecimal(100));//0.01x100=1 0.1x100=10

        BigDecimal leftprice50 = leftprice100.multiply(new BigDecimal(0.50));
        BigDecimal leftprice25 = leftprice100.multiply(new BigDecimal(0.25));
        BigDecimal leftprice15 = leftprice100.multiply(new BigDecimal(0.15));
        BigDecimal leftprice20 = leftprice100.multiply(new BigDecimal(0.2));
        BigDecimal leftprice10 = leftprice100.multiply(new BigDecimal(0.1));
        BigDecimal shifenyi = price.multiply(new BigDecimal(0.1));

        logger.debug("---------------------------------cutprice/forcut ptotal=" + ptotal);
        logger.debug("---------------------------------cutprice/forcut number=" + number);


        BigDecimal leftpricejun5 = leftprice100.divide(new BigDecimal(ptotal - number), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(5));
        BigDecimal leftpricejun4 = leftprice100.divide(new BigDecimal(ptotal - number), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(4));
        BigDecimal leftpricejun2 = leftprice100.divide(new BigDecimal(ptotal - number), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(2));
        if (leftpricejun4.doubleValue() > leftprice100.doubleValue()) leftpricejun4 = leftprice100;
        if (leftpricejun2.doubleValue() > leftprice100.doubleValue()) leftpricejun2 = leftprice100;


        BigDecimal oneyuan = new BigDecimal(100);
        BigDecimal twoyuan = new BigDecimal(200);
        BigDecimal twomao = new BigDecimal(20);
        BigDecimal yimao = new BigDecimal(10);

        BigDecimal ten = new BigDecimal(10);
        BigDecimal one = new BigDecimal(1);
        BigDecimal two = new BigDecimal(2);
        Boolean highqx = true;
        //是否在平台首次帮砍价
        int allcout = cutpriceHelpService.selectCount(new EntityWrapper<CutpriceHelp>().eq("uid", uid));

        BigDecimal cut = leftprice;
        if (ptotal - number == 1 || leftprice100.doubleValue() < ten.doubleValue()) {
            cut = leftprice;
            cutpriceopen.setEndtime(new Date());
            cutpriceopen.setStatus(PTstatus.ok.getVal());
        } else {

            int startday = Integer.parseInt(DateUtil.addToday(-7, "YYYYMMdd"));
            int startday30 = Integer.parseInt(DateUtil.addToday(-30, "YYYYMMdd"));
            int endday = Integer.parseInt(DateUtil.addToday(0, "YYYYMMdd"));
            logger.debug("-----------------------------------cutprice/forcut startday=" + startday);
            logger.debug("-----------------------------------cutprice/forcut endday=" + endday);

            //当日砍价数
            int couttoday = cutpriceHelpService.selectCount(new EntityWrapper<CutpriceHelp>()
                    .eq("uid", uid)
                    .eq("createday", endday));

            //判断近7天是否高权值砍价过
            int cout7 = cutpriceHelpService.selectCount(new EntityWrapper<CutpriceHelp>()
                    .eq("uid", uid)
                    .eq("highqz", 1)
                    .ge("createday", startday).le("createday", endday));

            //判断近30天是否砍价过
            int cout30 = cutpriceHelpService.selectCount(new EntityWrapper<CutpriceHelp>()
                    .eq("uid", uid)
                    .ge("createday", startday30).le("createday", endday));
            logger.debug("-----------------------------------cutprice/forcut allcout=" + allcout);
            logger.debug("-----------------------------------cutprice/forcut cout30=" + cout30);
            logger.debug("-----------------------------------cutprice/forcut number=" + number);

            while (cut.doubleValue() >= leftprice.doubleValue()) {

                if (allcout == 0) {
                    //首次帮砍||首次参与砍价
                    cut = leftprice20.divide(new BigDecimal(100)).add(RandSplitNumUtils.genRandPack(twomao.intValue()).divide(new BigDecimal(100)).setScale(2, RoundingMode.DOWN));
                    if (cut.doubleValue() <= two.doubleValue())
                        leftprice50.divide(new BigDecimal(100)).add(RandSplitNumUtils.genRandPack(twomao.intValue()).divide(new BigDecimal(100)).setScale(2, RoundingMode.DOWN));
                } else if (cout30 == 0) {
                    //近30日内没有砍价记录
                    cut = leftprice10.divide(new BigDecimal(100)).add(RandSplitNumUtils.genRandPack(twomao.intValue()).divide(new BigDecimal(100)).setScale(2, RoundingMode.DOWN));
                    if (cut.doubleValue() <= one.doubleValue())
                        leftprice20.divide(new BigDecimal(100)).add(RandSplitNumUtils.genRandPack(twomao.intValue()).divide(new BigDecimal(100)).setScale(2, RoundingMode.DOWN));
                } else if (number == 0) {
                    //是否在平台下参与过活动
                    int ocout = orderService.selectCount(new EntityWrapper<Order>()
                            .eq("uid", uid)
                            .ge("status", 2));
                    logger.debug("-----------------------------------cutprice/forcut ocout=" + ocout);

                    //新人首到0.25
                    cut = ocout < 1 ? RandSplitNumUtils.genRandPack(leftprice25.intValue()).divide(new BigDecimal(100)).setScale(2, RoundingMode.DOWN) :
                            RandSplitNumUtils.genRandPack(leftprice15.intValue()).divide(new BigDecimal(100)).setScale(2, RoundingMode.DOWN);

                } else if (number == 1) {
                    cut = couttoday >= 2 ? RandSplitNumUtils.genRandPack(leftprice10.doubleValue() > twoyuan.doubleValue() ? twoyuan.intValue() : leftprice10.intValue() == 0 ? yimao.intValue() : leftprice10.intValue()).divide(new BigDecimal(100)).setScale(2, RoundingMode.DOWN)
                            : RandSplitNumUtils.genRandPack(leftprice15.intValue()).divide(new BigDecimal(100)).setScale(2, RoundingMode.DOWN);
                } else if (number == 8) {
                    cut = couttoday >= 2 ? RandSplitNumUtils.genRandPack(leftprice10.doubleValue() > twoyuan.doubleValue() ? twoyuan.intValue() : leftprice10.intValue() == 0 ? yimao.intValue() : leftprice10.intValue()).divide(new BigDecimal(100)).setScale(2, RoundingMode.DOWN)
                            : RandSplitNumUtils.genRandPack(leftprice10.intValue() == 0 ? yimao.intValue() : leftprice10.intValue()).divide(new BigDecimal(100)).setScale(2, RoundingMode.DOWN);
                } else if (number == 18 || number == 28 || number == 38 || number == 48 || number == 58 || number == 68 || number == 78) {
                    cut = RandSplitNumUtils.genRandPack(leftpricejun4.intValue() == 0 ? yimao.intValue() : leftpricejun4.intValue()).divide(new BigDecimal(100)).setScale(2, RoundingMode.DOWN);
                } else {
                    //找人帮砍
                    cut = couttoday >= 3 ? RandSplitNumUtils.genRandPack(leftpricejun4.doubleValue() > twomao.doubleValue() ? twomao.intValue() : leftpricejun4.intValue() == 0 ? yimao.intValue() : leftpricejun4.intValue()).divide(new BigDecimal(100)).setScale(2, RoundingMode.DOWN) :
                            cout7 < 3 ? RandSplitNumUtils.genRandPack(leftpricejun4.intValue() == 0 ? yimao.intValue() : leftpricejun4.intValue()).divide(new BigDecimal(100)).setScale(2, RoundingMode.DOWN) :
                                    RandSplitNumUtils.genRandPack(leftpricejun2.intValue() == 0 ? yimao.intValue() : leftpricejun2.intValue()).divide(new BigDecimal(100)).setScale(2, RoundingMode.DOWN);
                }
                cut = cut.setScale(2, RoundingMode.DOWN);
                logger.debug("-----------------------------------cutprice/forcut cut=" + cut);
            }
        }

        // 更新当前砍价活动实例t_cutprice_open
        cutpriceopen.setNumber(number + 1);
        cutpriceopen.setTotalcutPrice(cutpriceopen.getTotalcutPrice().add(cut));
        cutpriceopen.setCurprice(cutpriceopen.getCurprice().subtract(cut));
        kover = cutpriceopen.getCurprice().doubleValue() == 0;

        Order norder = new Order();
        norder.setId(cutpriceopen.getOid());
        norder.setRealpay(cutpriceopen.getCurprice());
        norder.setModifier(ObjectUtil.getUid());
        norder.setModifytime(new Date());
//        norder.setSaleprice(cutpriceopen.getCurprice());
        if (kover) {
            Order order = orderService.selectById(cutpriceopen.getOid());
            norder.setDiscount(order.getTotal());
            norder.setPaytime(new Date());

            //砍价成功状态
            norder.setStatus(order.getGtype() == 1 && (order.getShipperMethod() != null && order.getShipperMethod() < 4 && order.getShipperMethod() >= 1) ?
                    StatusEnum.forsend.getVal() : StatusEnum.receving.getVal());

            //更新商品信息
            Goods ngoods = new Goods();
            ngoods.setId(order.getGid());
            ngoods.setCanyushu(goods.getCanyushu() == null ? 1 : goods.getCanyushu() + 1);
            //商品订单数
            ngoods.setNumberOrders(goods.getNumberOrders() + 1);
            //商品销量
            ngoods.setNumberSale(goods.getNumberSale() == null ? order.getGoodsNumber() : goods.getNumberSale() + order.getGoodsNumber());

            if (goods.getStores() != null && goods.getStores().intValue() > 0) {
                ngoods.setStores(goods.getStores() - order.getGoodsNumber());
                goods.setStores(goods.getStores() - order.getGoodsNumber());
            }
            if (goods.getStores() != null & goods.getStores().intValue() <= 0) {
                ngoods.setStatus(Gstatus.over.getVal());
            }
            ngoods.updateById();

            //更新砍价信息
            cutpriceopen.setEndtime(new Date());
            cutpriceopen.setStatus(PTstatus.ok.getVal());

            //如果库存为零，砍价结束
            if (goods.getStores() <= 0) {
                //更新所有未成交订单为活动失败状态
                Order unorder = new Order();
                unorder.setGid(goods.getId());
                unorder.setStatus(StatusEnum.cancel.getVal());
                unorder.setRemark("该活动商品已售完，订单取消，欢迎下次再参与");
                unorder.setModifytime(new Date());
                orderService.update(unorder, new EntityWrapper<Order>()
                        .eq("status", 1).eq("gid", goods.getId()));

                //更新订单商品
                OrderGoods unorderGoods = new OrderGoods();
                unorderGoods.setGid(goods.getId());
                unorderGoods.setStatus(StatusEnum.cancel.getVal());
                unorderGoods.setModifytime(new Date());

                orderGoodsService.update(unorderGoods, new EntityWrapper<OrderGoods>()
                        .eq("status", 1).eq("gid", goods.getId()));

                //更新砍价订单(正在进行的砍价活动)
                CutpriceOpen cutpriceOpen = new CutpriceOpen();
                cutpriceOpen.setStatus(0);
                cutpriceOpen.setModifytime(new Date());
                cutpriceOpenService.update(cutpriceOpen, new EntityWrapper<CutpriceOpen>()
                        .eq("status", 1).eq("gid", goods.getId()));
            }
        }

        norder.updateById();

        cutpriceopen.setModifytime(new Date());
        cutpriceopen.setModifier(ObjectUtil.getUid());

        cutpriceopen.updateById();

        // 插入一次砍价实例t_cutprice_help
        CutpriceHelp help = new CutpriceHelp();
        help.setCoid(ptoid);
        help.setGid(cutpriceopen.getGid());
        help.setOid(cutpriceopen.getOid());

        help.setMid(ObjectUtil.getMid());
        help.setMpid(ObjectUtil.getMpid());
        help.setUid(ObjectUtil.getUid());
        help.setSid(ObjectUtil.getSid());

        help.setHighqz(cut.doubleValue() >= shifenyi.doubleValue() ? 1 : -1);

        //新用户首次砍价help.setIsnew();
        help.setIsnew(allcout == 0 ? 1 : -1);

        help.setCutprice(cut);
        help.setLeftprice(cutpriceopen.getCurprice());

        User ruser = redisService.getUser();

        help.setAvatarpic(ruser.getAvatarPic());
        help.setNickname(ruser.getNickName());

        help.setRemark(remark);
        help.setCreatetime(new Date());
        help.setCreateday(Integer.parseInt(DateUtil.getToday("YYYYMMdd")));
        help.insert();

        if (help.getSid() != null) {
            StoreStat storeStat = new StoreStat();
            storeStat.setStoreid(help.getSid());
            storeStat.setUsers(orderService.getHdCanyushu(help.getSid()));

            storeStat.setModifytime(new Date());
            storeStat.setMpid(help.getUid());

            storeStat.updateById();
        }

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("isnew", help.getIsnew());
        map.put("cut", cut);
        map.put("left", cutpriceopen.getCurprice().subtract(cutpriceopen.getMinprice()));

        List<CutpriceHelp> cutlist = cutpriceHelpService.selectList(new EntityWrapper<CutpriceHelp>()
                .setSqlSelect("distinct uid,avatarpic,cutprice,nickname,createtime,isnew ")
                .eq("coid", ptoid).orderBy("id"));
        cutpriceopen.setCutlist(cutlist);
        map.put("kanjia", cutpriceopen);

        Page page = new Page(1, 50);
        List<CutpriceHelp> kanyuanbang = cutpriceHelpService.selectPage(page, new EntityWrapper<CutpriceHelp>()
                .eq("gid", cutpriceopen.getGid()).orderBy("cutprice", false)).getRecords();
        map.put("kanyuanbang", kanyuanbang);

        List<CutpriceHelp> kanyuan = cutpriceHelpService.selectPage(page, new EntityWrapper<CutpriceHelp>()
                .setSqlSelect("distinct uid,avatarpic,cutprice ")
                .eq("gid", cutpriceopen.getGid()).orderBy("cutprice", false)).getRecords();
        map.put("kanyuan", kanyuan);

        info.setInfo(map);

        return info;
    }

    @RequestMapping("/api/cutpriceopen/detail")
    @ResponseBody
    public Jinfo getCutpriceOpenDetailById(@RequestParam("token") String token,
                                           @RequestParam("id") long id, HttpServletRequest req
    ) {
        Jinfo info = new Jinfo();
        CutpriceOpen cutpriceopen = cutpriceOpenService.selectById(id);
        info.setInfo(cutpriceopen);
        return info;
    }

    @RequestMapping("/api/cutprice/other/list")
    @ResponseBody
    public Jinfo getCutpriceOtherList(@RequestParam("coid") Long coid,
                                      @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                                      @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                      HttpServletRequest req
    ) {
        Jinfo info = new Jinfo();
        if (pageSize == null) pageSize = 10;
        Page page = new Page(pageIndex, pageSize);
        Page<CutpriceHelp> pagecut = cutpriceHelpService.selectPage(page, new EntityWrapper<CutpriceHelp>()
                .eq("coid", coid).orderBy("cutprice", false));
        info.setInfo(pagecut.getRecords());
        return info;
    }

    @RequestMapping("/api/cutprice/detail")
    @ResponseBody
    public Jinfo cutpriceDetail(@RequestParam("suid") String suid,
                                @RequestParam("isnew") int isnew,
                                @RequestParam("coid") Long coid,
                                @RequestParam("gid") Long gid
    ) {
        Jinfo info = new Jinfo();

        CutpriceOpen cutpriceopen = cutpriceOpenService.selectById(coid);
        Cutprice Cutprice = cutpriceService.selectById(cutpriceopen.getCid());
        CutpriceHelp cutpriceHelp = cutpriceHelpService.selectOne(new EntityWrapper<CutpriceHelp>()
                .eq("coid", coid)
                .eq("uid", ObjectUtil.getUid()));

        cutpriceopen.setInfo(Cutprice.getInfo());
        if (isnew == 1) {
            // 新发起的砍价活动
            cutpriceopen.setId(null);

            cutpriceopen.setCurprice(cutpriceopen.getPrice());
            cutpriceopen.setTotalcutPrice(new BigDecimal(0));
            cutpriceopen.setCreatetime(new Date());
            cutpriceopen.setNumber(0);
            cutpriceopen.setUid(ObjectUtil.getUid());//
            // 本人发起的砍价却别他人发起的砍价state=0,status=1 uid=uid
            // 商家发起的砍价默认state=1,status=2 uid=null
            cutpriceopen.setStatus(1);// 默认未开始
            cutpriceopen.insert();
        }

        if (isnew == 0 && cutpriceHelp != null && cutpriceHelp.getUid() == ObjectUtil.getUid()) {
            cutpriceopen.setHelpPrice(cutpriceHelp.getCutprice());
            cutpriceopen.setHasCut(true);
        } else {
            cutpriceopen.setHasCut(false);
        }

        List<Order> orders = orderService.selectList(new EntityWrapper<Order>().eq("gid", gid).eq("uid", ObjectUtil.getUid()));
//        List<CutpriceHelp> orders = cutpriceHelpService.selectList(new EntityWrapper<CutpriceHelp>().eq("gid", gid).eq("uid", ObjectUtil.getUid()));
        // 之前参与过砍价购买过的叫已购买
        if (orders != null && orders.size() > 0) {
            cutpriceopen.setHasOrder(true);
        } else {
            cutpriceopen.setHasOrder(false);
        }

        info.setInfo(cutpriceopen);
        return info;
    }

    @RequestMapping("/api/cutpriceopen/add")
    @ResponseBody
    public Jinfo cutpriceopenAdd(@Valid CutpriceOpen cutpriceopen,
                                 BindingResult bindingResult, HttpServletRequest req) {
        Jinfo info = new Jinfo();
        // 字段校验
        if (bindingResult.hasErrors()) {
            logger.debug("There are errors! {}", bindingResult);
            info.setMsg("There are errors! " + bindingResult);
            info.setCode(400);
            return info;
        }
        cutpriceopen.setCreatetime(new Date());
        cutpriceopen.insert();
        return info;
    }

    @RequestMapping("/api/cutpriceopen/modify")
    @ResponseBody
    public Jinfo cutpriceopenUpdate(HttpServletRequest req,
                                    CutpriceOpen cutpriceopen) {
        Jinfo info = new Jinfo();
        cutpriceopen.setModifytime(new Date());
        cutpriceopen.updateById();
        return info;
    }

}
